// pages/login/login.js

const userUtils = require("../../utils/user");
const validate = require('../../utils/validate');
const common = require('../../utils/common');
var pageUtils = require("../../utils/pageOptions.js");
const authServices = require('../../services/auth');
const constUtls = require('../../utils/const');
const notificationCenter = require('../../thridLib/WxNotificationCenter.js');

Page({
  data: {
    contentStatus: -1, //1有数据
    userInfo: null,
    submitInfo: {
      phone: '',
      code: '',
    },
    isLoginEnable: false,
    isGetCodeShow: true,
    lastTime: 60,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //1.禁止转发
    wx.hideShareMenu();
    //2.注册通知
    this.registNotification();
    //3.初始化数据
    this.initData();
    this.wxLogin()
  },
  //注册通知，当自提点切换的时候，更新数据
  registNotification: function () {
    var that = this;
    notificationCenter.addNotification(constUtls.getCodeSucessNoti, that.getCodeSuccess, that);
  },
  //微信获取code成功
  getCodeSuccess: function () {
    this.setData({
      contentStatus: 1
    });
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //移除通知
    var that = this;
    notificationCenter.removeNotification(constUtls.getCodeSucessNoti, that);
  },
  //微信登录
  wxLogin: function () {
    wx.checkSession({
      success: res => {
        //session_key 未过期,正常使用
        authServices.wxLogin()
      },
      fail: (res) => {
        //获取code并缓存
        this.wxLogin();
      }
    });
  },
  //初始化数据
  initData: function () {
    let submitInfo = this.data.submitInfo;
    this.setData({
      userInfo: userUtils.getUserInfo(),
      submitInfo: submitInfo
    });
  },
  //手机号
  validatePhone: function (e) {
    this.setData({
        submitInfo: {
          ...this.data.submitInfo,
          phone: e.detail.value
        }
      },
      this.checkCanSubmit
    )
  },
  //验证码
  validateCode: function (e) {
    this.setData({
        submitInfo: {
          ...this.data.submitInfo,
          code: e.detail.value
        }
      },
      this.checkCanSubmit
    );
  },
  checkCanSubmit: function () {
    const {
      phone,
      code
    } = this.data.submitInfo
    if (phone && code) {
      this.setData({
        isLoginEnable: true
      })
      return true
    }
    this.setData({
      isLoginEnable: false
    })
    return false
  },
  //点击登录
  doLogin: function (e) {
    if (!this.data.isLoginEnable) return;
    if (!validate.isPhone(this.data.submitInfo.phone)) {
      common.showToast({
        content: '请输入正确的手机号!'
      });
      return
    }
    this.requestToLogin();
  },

  //请求登录
  requestToLogin: function () {
    const {
      phone: mobile,
      code: smsCode
    } = this.data.submitInfo
    let data = {
      loginType: 2,
      mobile,
      smsCode,
      // platform: 2,
    }
    authServices.doLogin(data).then(res => {
      userUtils.updateUserInfo(res.data);
      userUtils.setToken(res.data.token);
      let tmpPageOptions = pageUtils.pageOptionsInfo();
      if (tmpPageOptions) {
        wx.reLaunch({
          url: tmpPageOptions.url + tmpPageOptions.param
        });
      } else {
        // 2 团长 3推广员 4推广主管
        if (res.data.userType == 2 || res.data.userType == 3 || res.data.userType == 4) {
          wx.reLaunch({
            url: '/pages/index/index'
          })
        } else {
          wx.navigateTo({
            url: '/pages/non-tuan-user/index'
          })
        }
      }
      if (tmpPageOptions) {
        pageUtils.clearPageOptionsInfo();
      }
    }).catch(err => {
      common.log(err);
    });
  },
  //获取验证码
  onGetCode: function (e) {
    //手机号
    if (!this.data.submitInfo.phone) {
      common.showToast('手机号码不能为空!');
      return;
    }
    if (!validate.isPhone(this.data.submitInfo.phone)) {
      common.showToast('请输入正确的手机号!');
      return;
    }
    //请求获取手机验证码
    this.requestToGetLoginVerfication(this.data.submitInfo.phone);
  },

  //请求获取手机验证码
  requestToGetLoginVerfication: function (phone) {
    let data = {
      mobile: phone
    }
    authServices.getVerficationCode(data).then(res => {
      if (res.code == 600) {
        //解析base64数据，输入图形验证码
        wx.navigateTo({
          url: `/pages/loginImageCode/index?imgBase64Data=${res.data}&phone=${this.data.submitInfo.phone}`
        });
      }
      //倒计时
      this.countDwonVerify();
    }).catch(err => {
      common.log(err);
    });
  },
  //更新界面60秒后获取验证码
  countDwonVerify: function () {
    // 将获取验证码按钮隐藏60s，60s后再次显示
    this.setData({
      isGetCodeShow: false
    })
    let countdown = 60;
    const settime = () => {
      if (countdown === 0) {
        this.setData({
          isGetCodeShow: true
        })
        countdown = 60;
        return;
      }
      this.setData({
        isGetCodeShow: false,
        lastTime: countdown
      })
      countdown--;
      setTimeout(function () {
        settime()
      }, 1000)
    }
    settime();
  }
})
